<?php


namespace App\Kernel\Express;


use App\Constants\Express;
use App\Exception\BusinessException;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Guzzle\ClientFactory;

/**
 * 快递鸟
 * @author 陈奕文
 * @package App\Kernel\Express
 */
class KdBird
{
    /**
     * Guzzle协程客户端
     * @Inject()
     * @var ClientFactory
     */
    public $clientFactory;

    // 请求头
    public $headers = [
        'Content-Type' => 'application/x-www-form-urlencoded;charset=utf-8',
    ];

    /**
     * 订阅订单追踪
     * @param $data
     * @param int $request_type
     * @return array|string
     */
    public function orderTracesSubByJson($data, $request_type = 1008)
    {
        $data = json_encode($data);
        $requestData = urlencode($data);
        $requestUrl = config('express.req_url');
        $options = [];
        try {
            $client = $this->clientFactory->create($options);
            $response = $client->request('POST', $requestUrl, [
                'headers' => $this->headers,
                'form_params' => [
                    'RequestData' => $requestData,
                    'EBusinessID' => config('express.e_business_id'),
                    'RequestType' => $request_type,
                    'DataSign' => $this->encrypt($data, config('express.app_key')),
                    'DataType' => Express::BIRD_DATA_TYPE, // json类型
                ],
            ]);
            $body = $response->getBody();
            $resp = $body->getContents();

            $resp = json_decode($resp, true);

        }catch (\Exception $e) {
            throw new BusinessException(400,$e->getMessage());
        }

        return $resp;
    }

    /**
     * 电商Sign签名生成
     * @param mixed $data data 内容
     * @param mixed $app_key app_key Appkey
     * @return string DataSign签名
     */
    public function encrypt($data, $app_key) {
        return urlencode(base64_encode(md5($data.$app_key)));
    }

    /**
     * 没有url编码的签名
     * @param $data
     * @param $app_key
     * @return string
     */
    public function encryptNotUrlEncode($data, $app_key)
    {
        return base64_encode(md5($data.$app_key));
    }

    /**
     * 返回规范数据
     * @param bool $success
     * @param string $reason
     * @return array
     */
    public function show($success = true, $reason = '')
    {
        return [
            'EBusinessID' => config('express.e_business_id'),
            'UpdateTime' => date("Y-m-d H:i:s"),
            'Success' => $success,
            'Reason' => $reason,
        ];
    }

}